<?php
namespace app\controllers\article;

include APP_PATH . 'vendor/autoload.php';
use app\models\ArticleModel;
use app\models\TagModel;
use Parsedown;
use app\controllers\BaseController;

class IndexController extends BaseController
{
    protected $preRead = 'cRead';

    public function index($param)
    {
        if (!$param) {
            $this->error(ErrorCode['ParamMiss']);
        }
        $postId = (int)$param[0];
        if ($postId < 1) {
            $this->error(ErrorCode['ParamWrong']);
        }
        $ret = ['code' => 0, 'message' => ''];
        try {
            $ArticleModel = new ArticleModel();
            $post = $ArticleModel->findOne($postId);
            if (!$post) {
                $ret['message'] = "文章{$postId}不存在";
                $this->error($ret);
            }
            $sCookie = $this->preRead . $postId;
            if (!isset($_COOKIE[$sCookie]) || !$_COOKIE[$sCookie]) {
                $ArticleModel->incRead($postId);
                \setcookie($sCookie, 1, time() + 7200);
            }
            $aHotPosts = $ArticleModel->findHots();
            $aTags = (new TagModel())->findTags(0, 0, 'id');
            $Parsedown = new Parsedown();
            $this->assign('title', $post['title']);
            $this->assign('author', $post['author']);
            $this->assign('time', $post['time']);
            $this->assign('content', $Parsedown->text($post['content']));
            $this->assign('read', $post['read']);
            $this->assign('tags', $aTags);
            $this->assign('hots', $aHotPosts);
            $this->render();
        } catch (Exception $e) {
            $this->error(['code' => $e->getCode(), 'message' => $e->getMessage()]);
        }
    }
}